Data sharing using zustand

  • 1. Step
    zustand is used to access and update the state (data) from any component

    Step 1: Install Zustand

    
                    npm install zustand
                  

    Step 2: Create Store

    src/store/useCounterStore.js

    
    
    import { create } from 'zustand';
    
    const useCounterStore = create((set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
      decrement: () => set((state) => ({ count: state.count - 1 })),
    }));
    
    export default useCounterStore;
    
    

    Step 3: Use the Store in Components

    
      import useCounterStore from './store/useCounterStore';
    
    function App() {
      const { count, increment, decrement } = useCounterStore();
    
      return (
        <div style={{ textAlign: 'center', marginTop: '50px' }}>
          <h1>Zustand Counter</h1>
          <h2>{count}</h2>
          <button onClick={increment}>+</button>{' '}
          <button onClick={decrement}>-</button>
        </div>
      );
    }
    
    export default App;